const http = require("http");
const fs = require("fs");
const fs_writeAsJSON = require("./fs_writeasjson");
const json2xls = require('json2xls');
const XLSX = require('xlsx');
// const fs_writeTextContent=require("./fs_writeTextContent")
// const parsePathJSON=require("./fs_parsePathJSON")
const app = require("./modules/routes")
http.createServer(app).listen(6607, () => {
    console.log('服务已启动，6607 端口监听中');
});

app.post("/writeText", function writeText(req, res, query) {
    // console.log(query);
    var body = "";
    req.on('data', function (chunk) {
        // 获取内容
        body += chunk;
        // console.log(chunk);
    });
    // 存储地址
    let filepath = query.filepath;
    // 文件名
    let filename = query.filename;
    // 检查"/"是否在末尾
    if (filepath.charAt(filepath.length - 1) != '/') {
        filepath = filepath + "/"
    }
    console.log(filename)

    let stringd = filepath;
    if (filename && filepath) {
        stringd = stringd + filename;
        req.on("end", function () {
            console.log(body);
            // 写入
            let words = "./" + stringd;
            fs.writeFile(words, body, (err) => {
                if (err) {
                    console.log(err);
                    res.setHeader("Access-Control-Allow-Origin", "*");
                    res.send_tah("文件写入成功！！！");
                    return;
                }
                console.log("successful writefile!!");
                res.setHeader("Access-Control-Allow-Origin", "*");
                res.send_tah("文件写入成功！！！");
            })
        })
    } else if (filepath) {
        stringd = stringd.substr(0, stringd.length - 1)
        req.on("end", function () {
            console.log(body);
            // 写入
            let text = "./" + stringd;
            fs.mkdir(text, (err) => {
                if (err) {
                    console.log(err);
                    res.setHeader("Access-Control-Allow-Origin", "*");
                    res.send_tah("文件夹创建成功！！！");
                    return;
                }
                console.log("successful buildDir!!");
                res.setHeader("Access-Control-Allow-Origin", "*");
                res.send_tah("文件夹创建成功！！！");
            })
        })
    }
    console.log(stringd)
});

app.get("/deleteText", function writeText(req, res, query) {
    console.log(query);
    // 存储地址
    let filepath = query.filepath;
    // 文件名
    let filename = query.filename;
    // 检查"/"是否在末尾
    console.log(filepath);
    if (filepath.charAt(filepath.length - 1) != '/') {
        filepath = filepath + "/"
    }


    let stringd = filepath;
    if (filename && filepath) {
        stringd = stringd + filename;
        let text = "./" + stringd;
        fs.unlink(text, (err) => {
            if (err) {
                console.log(err);
                res.setHeader("Access-Control-Allow-Origin", "*");
                res.send_tah("文件删除失败！！！");
                return;
            }
            console.log("writefile fault!!");
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.send_tah("文件删除成功！！！");
        })
    } else if (filepath) {
        stringd = stringd.substr(0, stringd.length - 1)
        let text = "./" + stringd;
        fs.rmdir(text, (err) => {
            if (err) {
                console.log(err);
                res.setHeader("Access-Control-Allow-Origin", "*");
                res.send_tah("文件夹删除失败！！！ 只能删除空的文件夹！！！");
                return;
            }
            console.log("successful deleteDir!!");
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.send_tah("文件夹删除成功！！！");
        })
    }
    console.log(stringd)
});

app.post("/getDir", function parsePath_JSON(req, res) {
    // 要读取的目录名
    var path1 = 'textdata';
    function readdir_senddir(directary) {
        // var data = fs.readFileSync(way);
        // console.log("json获取路径：" + way);
        // if (data) {
        //     data = data.toString();
        // }
        // data = JSON.parse(data);
        data = directary.struct;
        // console.log(data);
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.writeHead(200, { 'Content-Type': 'application/json;charset="utf-8"' });
        res.end(JSON.stringify(data));
    }
    fs_writeAsJSON.fs_writeAsJSON(path1, readdir_senddir);
});

app.get("/getText", function getText(req, res, query) {
    query = decodeURIComponent(query.filename);
    console.log(query);
    dirobj = JSON.parse(fs.readFileSync("./dirData/textdataDir.json"));
    console.log("file location：" + dirobj.docpath[query]);
    let data = fs.readFileSync(dirobj.docpath[query]);
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
    res.end(data);
    console.log("***************************************************")
});

app.post("/login", function login(req, res, password, adm) {
    console.log("check passwords")
    let data = "";
    req.on("data", chunk => {
        data += chunk;
    })
    req.on("end", () => {
        if (data) {
            data = decodeURIComponent(data)
            let n = 0;
            let data1 = "{\"";
            while (data[n]) {
                if (data[n] == "=") {
                    data1 = data1 + "\"\:\"";
                } else if (data[n] == "&") {
                    data1 = data1 + "\"\,\"";
                } else {
                    data1 = data1 + data[n];
                }
                n++;
            }
            data1 = data1 + "\"}";
            // console.log(data1);
            data1 = JSON.parse(data1);
            // console.log(data1.txtPWD);
            // console.log(password[data1.txtUserName]);
            if (data1.txtPWD != password[data1.txtUserName] || password[Object.keys(data1)[0]]) {
                res.setHeader("Access-Control-Allow-Origin", "*");
                res.send_tah("密码或用户名错误！！！");
            } else {
                adm.admin = adm.tmpadmin;
                res.setHeader("Access-Control-Allow-Origin", "*");
                let page = fs.readFileSync("./static/index.html");
                res.send_tah(page);
            }
        }
    })
})
function encodeCell(row, col) {
    let a = "";
    return a + col + row
}
function isSame(a_name, b_type, c, num) {
    for (let k = 0; k < num; k++) {
        if (c[k].NAME == a_name && c[k].TYPE == b_type) {
            return k;
        }
    }
    return -1;
}
function dealData(worksheet) {
    let maxRow = worksheet["!ref"].slice(4)
    let num = 0;
    let new_sheet = [];
    let j = 0;
    for (let i = 3; i <= maxRow; i++) {
        j = isSame(worksheet[encodeCell(i, "G")].v, worksheet[encodeCell(i, "D")].v, new_sheet, num)
        if (j >= 0) {
            new_sheet[j].number++;
            new_sheet[j].FUEL = parseFloat((new_sheet[j].FUEL * (new_sheet[j].number - 1) + parseFloat(worksheet[encodeCell(i, "M")].v)) / new_sheet[j].number).toFixed(2);
            // console.log(new_sheet[j].NAME,new_sheet[j].TYPE,new_sheet[j].FUEL,new_sheet[j].number);
        } else {
            let obj = {

                NAME: worksheet[encodeCell(i, "G")].v,
                TYPE: worksheet[encodeCell(i, "D")].v,
                FUEL: parseFloat(worksheet[encodeCell(i, "M")].v).toFixed(2),
                number: 1
            }
            new_sheet.push(obj);
            num++;
        }
    }
    let xls = json2xls(new_sheet);
    fs.writeFileSync('./static/files/result.xlsx', xls, 'binary');
    return new_sheet;
}
app.post("/upload", function upload(req, res, query) {
    let data = "";
    req.on("data", chunk => {
        data += chunk;
    })
    req.on("end", () => {
        if (data) {
            // console.log(JSON.parse(data), 1);
            let workbook = JSON.parse(data);
            // console.log(workbook.Sheets[workbook.SheetNames[0]], 1);
            let worksheet = workbook.Sheets[workbook.SheetNames[0]]
            // console.log(worksheet["!ref"].slice(4), worksheet["!ref"].slice(3, 4));
            // console.log(worksheet['C5']);
            dealData(worksheet);
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.send_tah("准备就绪!!");
        }
    })
})
app.post("/vacabulary_get", function makewords(req, res, query) {
    console.log("/vacabulary_get")
    let workbook = XLSX.readFile('./data/考研英语5500大纲词汇.xlsx'); //workbook就是xls文档对象
    let sheetNames = workbook.SheetNames; //获取表明
    let worksheet = workbook.Sheets[sheetNames[0]]; //通过表明得到表对象
    var data = XLSX.utils.sheet_to_json(worksheet); //通过工具将表对象的数据读出来并转成json
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.writeHead(200, { 'Content-Type': 'application/json;charset="utf-8"' });
    res.end(JSON.stringify(data));
    let way = "./data/newjson1.json"
    const writer = fs.createWriteStream(way);
    writer.write(JSON.stringify(data));
})

app.post("/vacabulary_update", function makewords(req, res, query) {
    console.log("/vacabulary_update")
    let data = "";
    req.on("data", chunk => {
        data += chunk;
    })
    req.on("end", () => {
        if (data) {
            let workbook = XLSX.readFile('./data/考研英语5500大纲词汇.xlsx'); //workbook就是xls文档对象
            let sheetNames = workbook.SheetNames; //获取表明
            let worksheet = workbook.Sheets[sheetNames[0]]; //通过表明得到表对象
            let sheet = XLSX.utils.sheet_to_json(worksheet); //通过工具将表对象的数据读出来并转成json
            // let workbook = XLSX.utils.book_new();
            // let worksheet = XLSX.utils.json_to_sheet(JSON.parse(data));
            let vacabulary =JSON.parse(data)
            for(let i=0;i<vacabulary.length;i++){
                sheet[vacabulary[i]["num"]]["month"]=vacabulary[i]["month"];
                sheet[vacabulary[i]["num"]]["day"]=vacabulary[i]["day"];
                sheet[vacabulary[i]["num"]]["year"]=vacabulary[i]["year"];
                sheet[vacabulary[i]["num"]]["times"]=vacabulary[i]["times"];
                sheet[vacabulary[i]["num"]]["remeber"]=vacabulary[i]["remeber"];
            }
            let worksheet2 = XLSX.utils.json_to_sheet(sheet);
            let way = "./data/newjson2.json"
            const writer = fs.createWriteStream(way);
            writer.write(JSON.stringify( sheet));
            let workbook2 = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook2, worksheet2, "Sheet1");
            XLSX.writeFile(workbook2, './data/考研英语5500大纲词汇.xlsx');
        }
    })
})